<template>
  <div style="margin: 20px">
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item class="special" label="交易子品种名称">
        <el-select v-model="queryParam.data.subTypeName" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in subTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item class="special" label="交易名称">
        <el-select v-model="queryParam.data.subTypeName" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in subTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开始日期">
        <el-date-picker
          v-model="queryParam.data.startDate"
          type="date"
          placeholder="选择日期"
          @change="selectStartDate"
        />
      </el-form-item>
      <el-form-item label="结束日期">
        <el-date-picker
          v-model="queryParam.data.endDate"
          type="date"
          placeholder="选择日期"
          @change="selectStartDate"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="query">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="exportFile">导出EXCEl</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="showNewWindow">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table
      ref="multipleTable"
      :data="tableData"
      min-height="500px"
      border
      tooltip-effect="dark"
      style="width: 100%"
    >
      <el-table-column prop="" type="index" label="序号" width="55" align="center" />
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column show-overflow-tooltip prop="ID" label="id" width="300px" />
      <el-table-column prop="TABLE_NAME" label="时间" min-width="200px" />
      <el-table-column prop="COLUMN_NAME" label="机组id" min-width="200px" />
      <el-table-column prop="COLUMN_COMMENT" label="机组名称" min-width="200px" />
    </el-table>
    <!--分页-->
    <el-row style="margin-top:20px">
      <el-col style="height:30px;display:flex;justify-content:flex-end;align-items:center">
        <el-pagination
          :current-page="queryParam.pageInfo.pageNum"
          :page-sizes="queryParam.pageInfo.pageSizes"
          :page-size="queryParam.pageInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="queryParam.pageInfo.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-col>
    </el-row>
    <el-dialog :title="formInfo.title" :visible.sync="formInfo.visible">
      <el-form ref="dataForm" :rules="formInfo.rules" :model="formInfo.data" label-position="left" label-width="90px" style="width: 400px; margin-left:50px;">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formInfo.data.name" />
        </el-form-item>
        <el-form-item label="类型" prop="datatype">
          <el-select v-model="formInfo.data.datatype" class="filter-item" placeholder="请选择">
            <el-option v-for="item in formInfo.option.typeOption" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间" prop="createtime">
          <el-date-picker v-model="formInfo.data.createtime" type="datetime" placeholder="请选择时间" />
        </el-form-item>
        <el-form-item label="电量" prop="energy">
          <el-input v-model="formInfo.data.energy" />
        </el-form-item>
        <el-form-item label="附件" prop="file">
          <el-upload ref="upload" :action="uploadUrl" :on-remove="upRemove" :on-success="upSuccess" :file-list="formInfo.data.fileList">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formInfo.data.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formInfo.visible = false">
          取消
        </el-button>
        <el-button type="primary" @click="createOrUpdate()">
          保存
        </el-button>
      </div>
    </el-dialog>
    <!--    测试区域-->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="名称">
        <el-input v-model="demoTable.data.name" />
      </el-form-item>
      <el-form-item class="special" label="类型">
        <el-select v-model="demoTable.data.type" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in formInfo.option.typeOption"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开始日期">
        <el-date-picker
          v-model="demoTable.data.start"
          type="date"
          placeholder="选择日期"
        />
      </el-form-item>
      <el-form-item label="结束日期">
        <el-date-picker
          v-model="demoTable.data.end"
          type="date"
          placeholder="选择日期"
          @change="selectStartDate"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="demoQuery">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="demoAdd">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="demoEdit">编辑</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="demoDelete">删除</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="demoFormTest">表单提交测试</el-button>
      </el-form-item>
    </el-form>
    <!--   测试表格-->
    <el-table
      ref="demoTable"
      :data="demoTable.tableData"
      min-height="500px"
      border
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="demoTableSelected"
    >
      <el-table-column prop="" type="index" label="序号" width="55" align="center" />
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column show-overflow-tooltip prop="id" label="id" width="80px" />
      <el-table-column prop="name" label="名称" min-width="200px" />
      <el-table-column prop="createtime" label="创建时间" min-width="200px" />
      <el-table-column prop="energy" label="电量" min-width="200px" />
      <el-table-column prop="fileId" label="附件id" min-width="200px" />
      <el-table-column prop="filename" label="附件" min-width="200px">
        <template slot-scope="scope">
          <span style="color: #0E77D1;text-decoration: underline;cursor: pointer" @click="downloadFile(scope.row)">{{ scope.row.filename }}</span>
          <!--          <a :href="uploadUrl" target="downloadFile" class="cellLink">{{ scope.row.filename }}</a>-->
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" min-width="200px" />
    </el-table>
    <!--分页-->
    <el-row style="margin-top:20px">
      <el-col style="height:30px;display:flex;justify-content:flex-end;align-items:center">
        <el-pagination
          :current-page="demoTable.pageInfo.pageNum"
          :page-sizes="demoTable.pageInfo.pageSizes"
          :page-size="demoTable.pageInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="demoTable.pageInfo.total"
          @size-change="demoSizeChange"
          @current-change="demoCurrentChange"
        />
      </el-col>
    </el-row>
    <el-dialog :title="formInfo2.title" :visible.sync="formInfo2.visible">
      <el-form ref="dataForm2" :rules="formInfo2.rules" :model="formInfo2.data" label-position="left" label-width="90px" style="width: 400px; margin-left:50px;">
        <el-form-item label="电量" prop="energy">
          <el-input v-model="formInfo2.data.energy" />
        </el-form-item>
        <el-form-item label="附件" prop="file">
          <el-upload
            class="upload-demo"
            :limit="2"
            action=""
            :on-change="handleChange"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :file-list="formInfo2.data.fileList"
            :auto-upload="false"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2张</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formInfo2.visible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitForm()">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import StockPileApi from '../../api/StockPileApi'
import { encrypt } from '../../api/sm2'
import axios from 'axios'
import { exportExcel } from '@/utils/ExcelUtil.js'
import {Decrypt,Encrypt} from '@/api/aes'
export default {
  name: 'Crud',
  data() {
    const validateNumber = (rule, value, callback) => { // 包含小数的数字
      const reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g
      if (value === '') {
        callback(new Error('请输入内容'))
      } else if (!reg.test(value)) {
        callback(new Error('请输入数字'))
      } else {
        callback()
      }
    }
    return {
      subTypeList: [], // 交易子品种名称下拉框数据
      selectSubType: '', // 选中数据
      tableData: [], // 表格数据
      queryParam: { // 表格查询参数
        'data': {
          subTypeName: '',
          tradeName: '',
          startDate: '',
          endDate: ''
        },
        'pageInfo': { // 封装分页信息
          total: 0, // 总条数
          pageNum: 1,
          pageSize: 10,
          pageSizes: [10, 20, 50, 100, 200, 500, 1000] // 设置每页可显示的条数
        },
        fileName: ''
      },
      formInfo: { // 表单信息封装
        title: '', // 弹窗标题
        visible: false, // 弹窗是否可见
        rules: { // 表单校验规则
          name: [{ required: true, message: '请填写名称', trigger: 'blur' }],
          datatype: [{ required: true, message: 'type必选', trigger: 'change' }],
          createtime: [{ required: true, message: '时间必选', trigger: 'change' }],
          energy: [{ validator: validateNumber, required: true, message: '请输入数字', trigger: 'blur' }]
        },
        option: {
          typeOption: [
            { id: '1', name: '大用户' },
            { id: '6', name: '售电公司' }
          ]
        },
        data: {
          id: '',
          datatype: '',
          createtime: '',
          name: '',
          energy: '',
          remark: '',
          fileId: '',
          fileList: [{ name: '', url: '' }]
        }
      },
      demoTable: {
        tableData: [],
        selectedData: [],
        data: {
          name: '',
          type: '',
          start: '',
          end: ''
        },
        pageInfo: { // 封装分页信息
          total: 0, // 总条数
          pageNum: 1,
          pageSize: 10,
          pageSizes: [10, 20, 50, 100, 200, 500, 1000] // 设置每页可显示的条数
        }
      },
      formInfo2: { // 表单信息封装
        title: '测试表单带附件提交', // 弹窗标题
        visible: false, // 弹窗是否可见
        rules: { // 表单校验规则
          energy: [{ validator: validateNumber, required: true, message: '请输入数字', trigger: 'blur' }]
        },
        data: {
          energy: '',
          file: {},
          fileList: []
        }
      }
    }
  },
  computed: {
    uploadUrl: function() {
      return process.env.VUE_APP_DEV_API + '/stockPile/uploadFile'
    },
    downloadUrl: function() {
      return process.env.VUE_APP_DEV_API + '/stockPile/downloadFile'
    },
    uploadUrl2: function() {
      return process.env.VUE_APP_DEV_API + '/stockPile/updateProductImg'
    }
  },
  created() {
    axios.get('/user/userinfo').then(res=>{
      console.log(res)
    }).catch(err=>{
      console.error(err)
    })



    // 设置时间格式
    const myTime = new Date()
    myTime.setMonth(myTime.getMonth() + 1)
    if (myTime.getMonth() < 10) {
      this.queryParam.data.startDate = myTime.getFullYear() + '-' + ('0' + myTime.getMonth())
    } else {
      this.queryParam.data.startDate = myTime.getFullYear() + '-' + myTime.getMonth()
    }
    this.queryParam.data.endDate = this.queryParam.data.startDate
  },
  mounted() {
    // 加载下拉框数据
    this.initCombo()
    // 查询表格
    this.query()
    this.demoQuery()
  },
  methods: {
    initCombo() {
      StockPileApi.initComboData(null).then(res => {
        if (res.code === 200) {
          this.subTypeList = res.data
        }
      })
    },
    query() {
      // 校验
      // 调用后台接口
      StockPileApi.table(this.queryParam).then((res) => {
        // 设置表格数据
        this.tableData = res.data.list
        // 更新分页信息
        this.queryParam.pageInfo.total = res.data.total
        this.queryParam.pageInfo.pageNum = res.data.pageNum
        this.queryParam.pageInfo.pageSize = res.data.pageSize
      })
    },
    selectStartDate() {
      console.log(1)
    },
    handleSizeChange(val) {
      this.queryParam.pageInfo.pageSize = val
      this.query()
    },
    handleCurrentChange(val) {
      this.queryParam.pageInfo.pageNum = val
      this.query()
    },
    async exportFile() {
      const url = '/stockPile/exportExcel'
      // 在前台设置好导出的文件名
      this.queryParam.fileName = '表格导出.xlsx'
      exportExcel(url, this.queryParam)
    },
    showNewWindow() {
      this.formInfo.visible = true
    },
    demoSizeChange(val) {
      this.demoTable.pageInfo.pageSize = val
      this.demoQuery()
    },
    demoCurrentChange(val) {
      this.demoTable.pageInfo.pageNum = val
      this.demoQuery()
    },
    demoQuery() {
      // 校验
      this.demoTable.tableData = []
      // 调用后台接口
      StockPileApi.demoTable(this.demoTable).then((res) => {
        // 设置表格数据
        this.demoTable.tableData = res.data.list
        // 更新分页信息
        this.demoTable.pageInfo.total = res.data.total
        this.demoTable.pageInfo.pageNum = res.data.pageNum
        this.demoTable.pageInfo.pageSize = res.data.pageSize
      })
    },
    demoEdit() {
      // 获取选中行数据,没有或多选了进行提示
      if (this.demoTable.selectedData.length !== 1) {
        this.$vMessage({
          message: '请选中一条数据',
          type: 'info'
        })
        return
      }
      // 对表单数据进行填充(下拉框中的id是字符串类型的,设置value的时候一定要注意类型一致)
      this.demoTable.selectedData[0].datatype = this.demoTable.selectedData[0].datatype + ''
      // 对日期格式做单独处理，转为日期类型
      const selTime = this.demoTable.selectedData[0].createtime
      this.demoTable.selectedData[0].createtime = this.parseDate(selTime)
      // 使用深拷贝创建一个新的对象,防止出现表单修改导致表格数据同时修改的问题(也可以使用浅拷贝Object.assign({}, obj))
      this.formInfo.data = JSON.parse(JSON.stringify(this.demoTable.selectedData[0]))
      this.demoTable.selectedData[0].createtime = selTime
      // 设置附件的显示名称和fileId
      if (this.demoTable.selectedData[0].filename) {
        this.formInfo.data.fileList = [{ name: this.demoTable.selectedData[0].filename, url: '' }]
      }
      // 设置弹窗表单可见
      this.formInfo.visible = true
    },
    demoAdd() {
      // 将表单数据清空
      this.formInfo.data = {
        id: '',
        datatype: '',
        createtime: '',
        name: '',
        energy: '',
        remark: ''
      }
      // this.$refs['dataForm'].clearValidate()
      // 设置弹窗表单可见
      this.formInfo.visible = true
      if (this.$refs['dataForm']) {
        this.$refs['dataForm'].resetFields()
      }
    },
    demoDelete() {
      // 获取选中行数据,没有或多选了进行提示
      if (this.demoTable.selectedData.length === 0) {
        this.$vMessage({
          message: '请至少选择一条数据',
          type: 'info'
        })
        return
      }
      const ids = []
      for (let i = 0; i < this.demoTable.selectedData.length; i++) {
        const id = this.demoTable.selectedData[i].id
        ids.push(id)
      }
      StockPileApi.delete(ids).then((res) => {
        this.$vMessage({
          message: res.message,
          type: 'info'
        })
        this.demoQuery()
      })
    },
    demoTableSelected(val) {
      this.demoTable.selectedData = val
    },
    parseDate(strDate) {
      const st = strDate
      const a = st.split(' ')
      const b = a[0].split('-')
      const c = a[1].split(':')
      const date = new Date(b[0], b[1] - 1, b[2], c[0], c[1], c[2])
      return date
    },
    createOrUpdate() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) { // 校验通过
          StockPileApi.saveOrUpdate(this.formInfo.data).then((res) => {
            let message = ''
            if (res.data) {
              message = '保存成功!'
              this.formInfo.visible = false
              this.demoQuery()
            } else {
              message = '保存失败!'
            }
            this.$vMessage({
              message: message,
              type: 'info'
            })
          })
        }
      })
    },
    submitUpload() {
      console.log('submitUpload')
    },
    upSuccess(data) {
      if (data.status === 0) {
        console.log('上传成功')
        this.$refs.upload.clearFiles()
        this.formInfo.data.fileId = data.data.id
        this.formInfo.data.fileList = [{ name: data.data.filename, url: '' }]
        this.formInfo.visible = false
        this.formInfo.visible = true
      }
    },
    upRemove() {
      this.formInfo.data.fileList = []
      this.formInfo.data.fileId = ''
    },
    downloadFile(row) {
      // StockPileApi.downloadFile({ fileId: fileId }).then((res) => {
      // })
      const fileName = row.filename
      const fileId = row.fileId
      const param = new FormData() // 创建form对象
      param.append('fileId', fileId) // 通过append向form对象添加数据
      // withCredentials: true 使得后台可以接收表单数据 跨域请求
      const instance = axios.create({
        withCredentials: true,
        responseType: 'blob'
      })
      // url为后台接口
      instance.post(this.downloadUrl, param)
        .then(function(res) {
          console.log(res)
          const b = new Blob([res.data], { type: 'application/octet-stream' })
          // 根据传入的参数b创建一个指向该参数对象的URL
          const url = URL.createObjectURL(b)
          const link = document.createElement('a')
          // 设置导出的文件名
          link.download = fileName
          link.href = url
          // 点击获取文件
          link.click()
        }) // 成功返回信息 调用函数 函数需自己定义，此处后面省略
        .catch(function(e) {
        }) // 服务器错误 调用对应函数 函数需自己定义，此处后面省略
    },
    demoFormTest() {
      // 将表单数据清空
      this.formInfo2.data = {
        energy: '',
        fileId: '',
        fileList: []
      }
      // 设置弹窗表单可见
      this.formInfo2.visible = true
      if (this.$refs['dataForm2']) {
        this.$refs['dataForm2'].resetFields()
      }
    },
    resetForm(formName) {
      this.formInfo2.data.fileList = []
      this.$refs[formName].resetFields()
    },
    handleChange(file, fileList) {
      this.formInfo2.data.fileList = fileList.slice(-2)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`超出上传限制`)
    },
    handleRemove(file, fileList) {
      this.formInfo2.data.fileList = fileList
    },
    submitForm() {
      this.$refs['dataForm2'].validate((valid) => {
        if (valid) {
          if (this.formInfo2.data.fileList === '') {
            this.$message({
              type: 'info',
              message: '上传照片不能为空'
            })
            return false
          }
          // var id=[[${session.loginUser.id}]]
          // this.ruleForm.userId=id;
          const formData = new FormData()
          this.formInfo2.data.fileList.forEach((file) => {
            formData.append('filename', file.raw)
          })
          formData.append('energy', this.formInfo2.data.energy)
          formData.append('name', '测试的name')
          formData.append('age', 24)
          formData.append('startTime', new Date())
          const config = { headers: { 'Content-Type': 'multipart/form-data' }}
          // 先上传图片，上传后返回图片地址
          axios.post(this.uploadUrl2, formData, config).then((resp) => {
            if (resp.data.success === true) {
              // 获取图片地址
              this.formInfo2.data.file = resp.data.data
            }
          })
        } else {
          this.$message({
            type: 'error',
            message: '系统出错'
          })
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
/deep/.table-th{
  text-align: center!important;
}
/deep/.table-lt{
  text-align: left!important;
}
/deep/.table-rt{
  text-align: right!important;
}
/deep/body .el-table th.gutter{
  display: table-cell!important;
}
/deep/.special .el-input{
  width:220px;
}
/deep/.el-table--scrollable-x .el-table__body-wrapper{
  min-height: 300px;
}
</style>
